"""
oySmedge.py by Erkan Ozgur Yilmaz (c) 2009

v0.0.1

Description:
------------
A simple python interface to Smedge that uses command line commands to
communicate with smedge

Version History:
----------------
v0.0.1
- the initial development version

TODO List:
----------

-------------------------------------------------------------------------------
"""



__version__ = '0.0.1'



import os



########################################################################
class Smedge(object):
    """Its a humble Python interface to smedge
    """
    
    #----------------------------------------------------------------------
    def __init__(self):
        # initialize variables
        self.endFrame = 10
        self.extraParameters = ''
        self.imageDir = ''
        self.imageFormat = ''
        self.jobName = ''
        self.killOverTime = 1200
        self.layerName = ''
        self.maxCPUs = -1
        self.multiThread = 1
        self.note = ''
        self.outputDir = ''
        self.packetSize = 1
        self.pool = 'Whole System'
        self.pools = [''] * 0
        self.priority = 100
        self.product = 'Maya'
        self.products = [''] * 0
        self.projectPath = ''
        self.sceneFullPath = ''
        self.startFrame = 1
        self.lastJobID = ''
    
    
    
    #----------------------------------------------------------------------
    def sendJob(self):
        # gather info and send
        
        # check if the sceneFullPath is empty
        if self.sceneFullPath == '':
            raise ValueError('set a scene to render')
        
        # check if the packet size is greather than 0
        if self.packetSize < 1:
            self.packetSize = 1
        
        # check if the user gave a jobName
        # if not find by your self
        if self.jobName == '':
            self.jobName = self.get_jobName_from_sceneFullPath()
    
    
    
    #----------------------------------------------------------------------
    def findProjectPath(self):
        pass
    
    
    
    
    #----------------------------------------------------------------------
    def get_jobName_from_sceneFullPath( self ):
        # jobName shold be in
        # 
        # sceneNameWithExtension : LayerNamme
        
        self.jobName = os.path.basename( self.sceneFullPath )
        
        if self.layerName != '':
            self.jobName += ' : ' + self.layerName






########################################################################
class Job(object):
    """It's a simple class that introduces a simple interface to the smedge job
    """
    
    
    
    def __init__(self,id):
        self._id = id
    
    
    
    def decrease(self):
        pass
    
    
    
    def delete(self):
        pass
    
    
    
    def increase(self):
        pass
    
    
    
    def pause(self):
        pass
    
    
    
    def pool(self, poolName ):
        pass
    
    
    
    def priority ( self, priority ):
        pass
    
    
    
    def resubmit ( self ):
        pass






########################################################################
class Client(object):
    """It's a simple class that introduces a simple interface to the smedge client
    """
    
    
    
    def __init__( self, clientName ):
        self._clientName
    
    
    
    def kill( self ):
        pass
    
    
    
    def disable( self ):
        pass
    
    
    
    def disable1( self ):
        pass
    
    
    
    def enable( self ):
        pass
    
    
    
    def enable1( self ):
        pass
    
    
    
    def toggle( self ):
        pass
    
    
    
    def toggle1( self ):
        pass
    
    
    
    def restrict( self ):
        pass
    
    
    
    def restart( self ):
        pass






########################################################################
class Nuke(object):
    """nuke interface to smedge
    """
    
    #----------------------------------------------------------------------
    def __init__(self):
    
    
    





########################################################################
class Maya(object):
    """maya interface to smedge
    """
    
    #----------------------------------------------------------------------
    def __init__(self):
        
    
    
    






def ssCollectDataAndRun():
    # needed fields
    # +startFrame
    # +endFrame
    # +packetSize
    # +priority
    # +projectPath
    # +jobName     in   ProjectName : scenename : layerName format
    # +layerName
    # +sceneFullPath
    
    import os
    # startFrame
    frameData = pm.intFieldGrp('oySTS_range_intField',q=True,v=True)
    startFrame = frameData[0]
    endFrame = frameData[1]
    packetSize = frameData[2]
    
    priority = pm.intSliderGrp('oySTS_priority_intSliderGrp',q=True,v=True)
    
    projectPath = os.path.realpath( pm.workspace.path )
    sceneFullPath = os.path.realpath( pm.sceneName() )
    
    projectName = projectPath.split(os.path.sep)[-1]    
    sceneName = sceneFullPath.split(os.path.sep)[-1]
    
    
    layers = pm.TextScrollList( 'oySTS_layers_scrollList' ).getSelectItem()
    
    keys = dict()
    keys['startFrame'] = startFrame
    keys['endFrame'] = endFrame
    keys['packetSize'] = packetSize
    keys['priority'] = priority
    keys['projectPath'] = projectPath
    keys['sceneFullPath'] = sceneFullPath
    
    for layer in layers:
        keys['layerName'] = layer
        keys['jobName'] = projectName + ' : ' + sceneName + ' : ' + layer
        
        layerNode = pm.RenderLayer(layer)
        if layerNode.hasAttr('renderRangeMin'):
            layerMin = layerNode.getAttr('renderRangeMin')
            if layerMin > startFrame:
                keys['startFrame'] = layerNode.getAttr('renderRangeMin')
            else:
                keys['startFrame'] = startFrame
        else:
            keys['startFrame'] = startFrame


        if layerNode.hasAttr('renderRangeMax'):
            layerMax = layerNode.getAttr('renderRangeMax')
            if layerMax < endFrame:
                keys['endFrame'] = layerNode.getAttr('renderRangeMax')
            else:
                keys['endFrame'] = endFrame
        else:
            keys['endFrame'] = endFrame
        
        sendToSmedge( **keys )



def sendToSmedge( **keys ):
    # get the information needed by smedge
    smrFile = createSmrFile( keys )
    import os
    
    progFilesDir = ''
    
    if os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64':
        progFilesDir ='C:\Program Files (x86)'
    else:
        progFilesDir ='C:\Program Files'
    
    command = r'"'+progFilesDir+'\Smedge\smedge.exe" -submit ' + smrFile
    
    print command
    import os
    os.system( command )



def createSmrFile( keys ):
    
    smrFilePath = keys['sceneFullPath'] + '.smr' 
    print 'smrFilePath : %s' % smrFilePath
    smrFile = open( smrFilePath, 'w' )
    
    smrFileContent = [""]
    smrFileContent.append( r'End = ' + str(keys['endFrame']) +'\n')
    smrFileContent.append( r'ExtraParameters = -preRender oyRenderOneLayer(\"' + keys['layerName'] + r'\")' +'\n')
    smrFileContent.append( r'ImageDir = '+'\n')
    smrFileContent.append( r'ImageFmt = '+'\n')
    smrFileContent.append( r'JobName = ' + keys['jobName'] +'\n')
    smrFileContent.append( r'KillOvertime = 1200' +'\n')
    smrFileContent.append( r'MaxCPUs = -1' +'\n')
    smrFileContent.append( r'MultiThread = 1' +'\n')
    smrFileContent.append( r'Note = Created with oyReferenceTools v1.0.0' +'\n')
    smrFileContent.append( r'OutputDir = ' +'\n')
    smrFileContent.append( r'Packet = ' + str(keys['packetSize']) +'\n')
    smrFileContent.append( r'Pool = Whole System' +'\n')
    smrFileContent.append( r'Priority = ' + str(keys['priority']) +'\n')
    smrFileContent.append( r'Product = MentalRayForMaya' +'\n')
    smrFileContent.append( r'Project = ' + keys['projectPath'] +'\n')
    smrFileContent.append( r'SceneName = ' + keys['sceneFullPath'] +'\n')
    smrFileContent.append( r'Start = ' + str(keys['startFrame']) +'\n')
    
    smrFile.writelines( smrFileContent )
    smrFile.close()
    
    return smrFilePath